package server.requesthandler;

import client.request.LoginRequestMessage;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.AttributeKey;
import io.netty.util.concurrent.GlobalEventExecutor;
import util.ChannelUtils;

/**
 * @Description 将用户信息存入ChannelUtils
 * @author czc
 */
public class LoginRequestHandler extends SimpleChannelInboundHandler<LoginRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, LoginRequestMessage msg) throws Exception {
        Channel channel = ctx.channel();

        AttributeKey<String> attrKey = AttributeKey.valueOf("nickName");
        ctx.channel().attr(attrKey).set(msg.getUsername());
        //ChannelUtils.putUserId(msg.getUsername(), channel);
        //System.out.println("当前在线用户为:"+ChannelUtils.getAllUserId());
        System.out.println(msg.getUsername() + "-----------上线了");
        //将新上线的用户的channel添加到map中
        ChannelUtils.putUserId(msg.getUsername(), channel);
        //将新上线的用户添加到map中
        String initialChannelGroup = "1";
        ChannelGroup channelGroup = ChannelUtils.getChannelGroup(initialChannelGroup);
        channelGroup.add(channel);
        ChannelUtils.putChannelGroupId(initialChannelGroup, channelGroup);
    }
}
